package thread.waitnotifypackage;

import java.util.HashMap;
import java.util.Queue;
import java.util.Random;

/**
 * 生产者
 */
public class Producer extends Thread {

    String producerName;
    int maxSize;
    int i = 0;
    private final Queue<Integer> queue;

    public Producer(Queue<Integer> queue, String producerName, int maxSize) {
        super(producerName);
        this.queue = queue;
        this.producerName = producerName;
        this.maxSize = maxSize;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (queue) {

                System.out.println("queue: " + queue);

                while (queue.size() == maxSize) {
                    try {
                        System.out.println("queue is full, the producer " + producerName + " is waiting");
                        // 当前阻塞啊啊啊啊啊
                        queue.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                System.out.println("[" + producerName + "]" + "producirng value:" + i);
                queue.offer(i++);
                queue.notifyAll(); // 此时不会释放锁 而是等线程执行完后再释放

                try {
                    Thread.sleep(new Random().nextInt(1000));
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }
        }
    }
}
